import { View } from '@tarojs/components';
import React, { useEffect, useState } from 'react';
import Taro from '@tarojs/taro';

function weappAnimation(moveX, startX) {
  const _animation = Taro.createAnimation({
    duration: 200,
    timingFunction: 'linear',
    delay: 50,
    transformOrigin: 'left top 0',
    success: function (res) {
      console.log(res);
    },
  });

  const minSwipe = Taro.$windowWidth * (1 / 4);

  if (moveX + minSwipe >= startX) {
    _animation.translateX(0).step();
  } else {
    _animation.translateX((-150 / 750) * Taro.$windowWidth).step();
  }

  return _animation;
}

function h5Animation(moveX, startX) {
  let style;
  const minSwipe = Taro.$windowWidth * (1 / 4);

  if (moveX + minSwipe >= startX) {
    style = {
      display: 'flex',
      transform: 'none',
    };
  } else {
    style = {
      display: 'flex',
      transform: `translateX(${(-150 / 750) * Taro.$windowWidth}px)`,
      transition: `200ms`,
    };
  }

  return style;
}

const ScrollDelete = ({ children }) => {
  const [animation, setAnimation] = useState('');
  const [startX, setStartX] = useState(0);

  const [style, setStyle] = useState({
    display: 'flex',
    alignItems: 'flex-end',
  });
  // 滑动开始
  const touchstart = (e) => {
    setStartX(e.changedTouches[0].clientX);
  };

  // 滑动开始
  const touchend = (e) => {
    const moveX = e.changedTouches[0].clientX;

    console.log({ moveX, startX, diff: startX - moveX });

    if (process.env.TARO_ENV === 'weapp') {
      setAnimation(weappAnimation(moveX, startX).export());
    } else if (process.env.TARO_ENV === 'h5') {
      setStyle(h5Animation(moveX, startX));
    }
  };

  useEffect(() => {}, []);

  return (
    <View
      className="ScrollDelete"
      style={style}
      onTouchStart={touchstart}
      onTouchEnd={touchend}
      animation={animation}
    >
      {children}
    </View>
  );
};

export default ScrollDelete;
